<template>
  <el-form ref="refForm" :model="form" :rules="rules">
    <el-form-item label="密码" prop="password">
      <el-input v-model.trim="form.password" type="password" clearable show-password />
    </el-form-item>
    <el-form-item label="确认密码" prop="confirm_password">
      <el-input v-model.trim="form.confirm_password" type="password" clearable show-password />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">修改密码</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { changePassword } from '@/api/system/user'
import { getInfo } from '@/api/system/auth'
import md5 from 'js-md5'
export default {
  props: {
    user: {
      type: Object,
      default: () => {
        return {
          id: 0,
          name: '',
          phone: '',
          avatar: ''
        }
      }
    }
  },
  data() {
    return {
      form: {
        id: 0,
        password: '',
        confirm_password: ''
      },
      rules: {
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '长度必须大于等于 6 个字符', trigger: 'blur' }
        ],
        confirm_password: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { min: 6, message: '长度必须大于等于 6 个字符', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUser()
  },
  methods: {
    getUser() {
      getInfo().then(res => {
        this.form.id = res.id || 0
      })
    },
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.form.password) {
        callback(new Error('密码不一致'))
      } else {
        callback()
      }
    },
    submit() {
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          const data = {
            id: this.form.id,
            password: md5(this.form.password),
            confirm_password: md5(this.form.confirm_password)
          }
          changePassword(data).then(res => {
            this.$message({
              message: '密码修改成功',
              type: 'success'
            })
            this.formVisible = false
          }).then(res => {})
        }
      })
    }
  }
}
</script>
